#include"DoubleLinkList.h"

Status ListInsert(DLinkList& L, int i, ElemType e)
{
	DLNode* pre=L;
	int j = 0;
	while (pre && j != i - 1)
	{
		pre = pre->next;
		j++;
	}
	if (i<1 || i>j + 1)
		return ERROR;
	/*进行插入*/
	DLinkList newnode = new DLNode;
	newnode->data = e;

	newnode->next = pre->next;
	if(pre->next)
	pre->next->prior = newnode;
	pre->next = newnode;
	newnode->prior = pre;
	return OK;
}

Status ListDelete(DLinkList& L, int i,ElemType& e)
{
	if (!L)
		return ERROR;
	//先找到待删除结点的前驱
	DLNode* pre = L;
	int j = 0;
	while (pre && j != i - 1)
	{
		pre = pre->next;
		++j;
	}
	if (i < 1 || i>j)
		return ERROR;
	//进行删除
	DLNode* del = pre->next;
	pre->next = del->next;
	del->next->prior = pre;
	delete del;
	return OK;
}

//按位置查找返回元素
ElemType ListQuery(DLinkList& L, int i)
{
	if (!L)
		exit(-1);
	DLNode* cur = L->next;
	int j = 1;
	while (cur && j != i)
	{
		cur = cur->next;
		++j;
	}
	return cur->data;
}

Status CreateList(DLinkList& L)
{
	/*双向链表初始化*/
	L = new DLNode;
	if (!L)
		return ERROR;
	L->prior = L->next = nullptr;

	char big_int[101];
	cout << "请输入一个大整数：(输入时需保有千分位符)" << endl;
	cin >> big_int;

	/*尾插法创建*/
	char* str_e=strtok(big_int,",");
	int i = 1;
	do
	{
		ElemType e = atoi(str_e);
		ListInsert(L, i++, e);
		str_e = strtok(NULL, ",");
	} while (str_e);
	return OK;
}


Status DisplayList(DLinkList& L)
{
	if (!L)
		return ERROR;
	DLNode* cur = L->next;
	do
	{
		if (cur == L->next)
			cout << cur->data;
		else
		printf("%03d", cur->data);
		cur = cur->next;
		if (cur)
			cout << ",";
	} while (cur);
	cout << endl;
	return OK;
}

void DestroyList(DLinkList L)
{
	if (!L)
		return;
	DLNode* cur = L;
	while (cur)
	{
		DLNode* PDel = cur;
		cur = cur->next;
		delete PDel;
	}
}